using System;
using System.Drawing;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.VideoSurveillance;
using NIPO.Data;
using NIPO.Plugins;

namespace NIPOCvPlugins.ObjectDetectorPlugin
{
    public class ObjectDetectionProcessingPlugin : ProcessingPlugin
    {
        private BlobTrackerAuto<Bgr> _tracker;
        private static MCvFont _font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0);

        #region Overrides of Plugin

        protected override void Initialize()
        {
            _tracker = new BlobTrackerAuto<Bgr>();
        }

        public override void Dispose()
        {
            _tracker.Dispose();
        }

        public override bool IsConfigured
        {
            get { return true; }
        }

        #endregion

        #region Overrides of IPOPlugin

        public override void Reset()
        {
            _tracker = null;
        }

        #endregion

        #region Overrides of ProcessingPlugin

        public override void ProcessData(object sender, NIPOEventArgs e)
        {
            Image<Bgr, byte> image = (e.Data as GenericDTO<Image<Bgr, byte>>).Value;
            lock (this)
            {
                _tracker.Process(image);
            }

            image.Add(_tracker.ForgroundMask.Convert<Bgr, byte>());
            foreach (MCvBlob blob in _tracker)
            {
                image.Draw(Rectangle.Round(blob), new Bgr(255.0, 255.0, 255.0), 2);
                image.Draw(blob.ID.ToString(), ref _font, Point.Round(blob.Center), new Bgr(255.0, 255.0, 255.0));
            }

            RaiseNewData(new GenericDTO<Image<Bgr, byte>>(image, "EMGU/Image<Bgr,byte>", image.Bytes.Length,
                                                          DateTime.Now));
        }

        #endregion
    }
}